import json
import re
import requests
from Basic.base_log import log
def send_requests(url,method,data):
    #将获取到的数据分割成headers和param
    data_list = data.split("\n...\n")
    # data_list = data_list.replace('\n', 'as')
    log.info('未转化的data_list==%s' % data_list)
    #将字符串转化成JSON
    try:
        headers = str_json(data_list[0])
        param = str_json(data_list[1])
        log.info('headers= %s'%(headers))
        log.info('param= %s' % (param))
    except Exception as e:
        log.error('json格式转化出错：{0}'.format(e))
        return
    if method == 'get' or method == 'GET' or method == 'Get':
        log.info('url= %s'%url)
        log.info('headers= %s' % headers)
        log.info('param= %s' % param)
        res = requests.get(url, headers, verify=False)
    elif method == 'post' or method == 'POST' or method == 'Post':
        res = requests.post(url=url, headers=headers, data=param, verify=False)
    else:
        return log.error("请求方式出错，请传GET或POST")
    log.info('请求结果：%s' % (res.text))
    return res.text
    # try:
    #     if method == 'get' or method == 'GET' or method == 'Get':
    #         r = requests.get(url=url, headers=headers, verify=False)
    #     elif method == 'post' or method == 'POST' or method == 'Post':
    #         r = requests.post(url=url, headers=headers, json=param, verify=False)
    #     else:
    #         return log.error("请求方式出错，请传GET或POST")
    #     log.info('请求结果：%s'% (r.json()))
    #     return r.json()
    # except Exception as e:
    #     log.error("request报错：{0}".format(e))
    #     return "request报错：{0}".format(e)


def json_if(da):
    try:
        json_object = json.loads(da)
    except ValueError as e:
        return False
    return True

#字符串转化 格式如下：
a = """age: 6876518
ali-swift-global-savetime: 1617988194
content-encoding: gzip
content-md5: vJP2095ZNKe4OPPtQHVdJA==
content-type: text/css; charset=utf-8
date: Fri, 09 Apr 2021 17:09:54 GMT
eagleid: af2a518f16248647123952313e
last-modified: Tue, 27 Oct 2020 09:04:40 GMT
server: Tengine
timing-allow-origin: *"""

''' 将浏览器复制的请求内容转化成json '''
def str_json(str):
    strlist = []
    # 先提取每行的值 （标志为换行符）
    strline = re.split(r'\n', str)
    # print('aline=== %s' % strline)
    # 通过第一个冒号空格分割字符串
    for i in strline:
        strlist.append(re.split(r'[:]\s', i))
    # print('alist=== %s' % strlist)
    # 将列表转化为字典，将字典转化为json
    strJson = json.dumps(dict(strlist))
    print(strJson)
    return strJson
# str_json(a)


# headers = '{"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}'
# r = requests.get('https://www.baidu.com')
# print(r.json)




"""
正则表达式提取规则
.   任意字符

*    重复零次或多次
+    重复一次或多次，不包含本身
？   重复零次或一次

^ $  开始和结束

( )  一组
[ ]  任选一种
{ }

"""
